from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from django.core.paginator import Paginator

from .ser import *

from .models import *

from utils.comm import *

import random
# 加密导包
from django.contrib.auth.hashers import make_password,check_password
from utils.comm import get_redis


# Create your views here.

# 新闻表操作
class NewMang(APIView):
    # 添加操作
    def post(self,request):
        # 调用序列化器
        ser=NewSer(data=request.data)
        # 验证
        if ser.is_valid():
            # 保存
            ser.save()
            # 返回
            return Response({'code':'200'})
        else:
            print(ser.errors)
            return Response({'code':'10010'})

class Getnew(APIView):
    # 查看
    def get(self,request):
        us=New.objects.all()
        # 调用序列化器
        ser=NewSer(us,many=True)
        # 返回
        return Response({'code':200,'list':ser.data})

    # 登录
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        us=New.objects.filter(username=username).first()
        if us:
            if password==us.password:
                return Response({'code':200,'uid':us.id})
            else:
                return Response({'code':10010,'mes':'密码不正确'})
        else:
            return Response({'code':10010,'mes':'没有该用户'})

# 详情
class News(APIView):
    def post(self,request):
        userid=request.data.get('userid')
        newsid=request.data.get('newsid')

        us=New.objects.filter(id=newsid).first()
        ser=NewSer(us)

        coon=get_redis()
    # 自增
        count=coon.hincrby(userid,newsid)
        print(count)
        if count >= 3:
            return Response({'code':20020})
        else:
            return Response({'code':200,'list':ser.data})

    def get(self,request):
        us=New.objects.all()
        ser=NewSer(us,many=True)
        return Response({'code':200,'list':ser.data})